<!-- 词云 -->
<template>
  <div>
    <div class="  text-slate-400 ">【导演词云】</div>
    <div ref="target" class="w-full h-full"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from "vue";
import * as echarts from "echarts";
import "echarts-wordcloud";
const props = defineProps({
  data: Array,
});
// console.log("props:", props);
let chart = ref(null);
const target = ref(null);
onMounted(() => {
  chart = echarts.init(target.value);
  ChartInit(); // 将 chart 传递给 ChartInit 函数
});
const randomRgb = () => {
  const r = Math.floor(Math.random() * 255);
  const g = Math.floor(Math.random() * 255);
  const b = Math.floor(Math.random() * 255);
  return `rgb(${r},${g},${b})`;
};

const ChartInit = () => {
  if (!props.data || props.data.length === 0) {
    console.log("No data to display");
    return;
  }
  const directorCount = props.data.reduce((acc, item) => {
    if (item !== undefined && item !== null) {
      acc[item] = (acc[item] || 0) + 1;
    }
    return acc;
  }, {});
  const wordCloudData = Object.keys(directorCount).map(item => ({
    name: item,
    value: directorCount[item]
  }));
  const option = {
    series: [
      {
        type: "wordCloud",
        sizeRange: [1, 40],
        rotationRange: [0, 0],
        gridSize: 1,
        layoutAnimation: true,
        textStyle: {
          color: randomRgb,
        },
        emphasis: {
          textStyle: {
            fontWeight: "bold",
            color: "#000",
          },
        },
        data: wordCloudData,
      },
    ],
  };

  // console.log("option:", option); // 检查 option 对象
  try {
    chart.setOption(option);
  } catch (error) {
    console.error("Error setting option:", error);
  }
};

watch(() => props.data, ChartInit);
</script>

<style lang="scss" scoped></style>
